﻿@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>角色管理</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/layui/2.9.7/css/layui.css" />
</head>
<body>
    <div class="layui-container" style="margin-top: 20px;">
        <!-- 搜索栏 -->
        <div class="layui-form">
            <div class="layui-form-item">
                <label class="layui-form-label">角色名称</label>
                <div class="layui-input-inline">
                    <input type="text" id="roleName" class="layui-input" placeholder="请输入角色名称" />
                </div>
                <div class="layui-input-inline">
                    <select id="selRole" class="layui-select" lay-search>
                        <option value="">请选择角色</option>
                    </select>
                </div>
                <button class="layui-btn" id="searchBtn">查询</button>
                <button class="layui-btn layui-btn-normal" id="addBtn">添加</button>
            </div>
        </div>

        <!-- 角色列表 -->
        <table class="layui-table" id="roleTable" lay-size="sm" lay-filter="roleTableFilter">
            <tbody></tbody>
        </table>
    </div>

    <!-- 新增/编辑 模态框 -->
    <div id="roleModal" class="layui-form" style="display: none; padding: 20px;">
        <input type="hidden" id="roleId" />
        <div class="layui-form-item">
            <label class="layui-form-label">角色名称</label>
            <div class="layui-input-block">
                <input type="text" id="modalRoleName" class="layui-input" placeholder="请输入角色名称" lay-verify="required" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">角色说明</label>
            <div class="layui-input-block">
                <input type="text" id="modalDescription" class="layui-input" placeholder="请输入角色说明" />
            </div>
        </div>
    </div>

    <!-- 操作列模板 -->
    <script type="text/html" id="toolbar">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>

    <script src="~/Scripts/layui/layui.js"></script>
    <script>
        // 确保DOM加载完成后执行
        document.addEventListener('DOMContentLoaded', function () {
            console.log("页面DOM加载完成，初始化角色管理功能");

            layui.use(['table', 'form', 'jquery', 'layer'], function () {
                console.log("Layui组件加载完成");

                var table = layui.table;
                var form = layui.form;
                var $ = layui.$;
                var layer = layui.layer;

                // 初始化数据
                BindSelect();
                renderRoleTable();

                // 表格渲染函数
                function renderRoleTable(searchParams = {}) {
                    table.render({
                        elem: "#roleTable",
                        id: "myTable",
                        url: "/Role/GetData",
                        cols: [[
                            { field: 'RoleID', title: '编号', width: 100, sort: true },
                            { field: 'RoleName', title: '角色名称', width: 150 },
                            { field: 'RoleReMark', title: '备注' },
                            { fixed: 'right', title: '操作', width: 200, templet: '#toolbar' }
                        ]],
                        page: true,
                        limit: 5,
                        limits: [5, 10, 15, 20],
                        where: searchParams,
                        done: function (res) {
                            console.log("表格数据加载完成，共" + (res.data ? res.data.length : 0) + "条数据");
                        }
                    });
                }

                // 搜索按钮事件
                $("#searchBtn").click(function () {
                    var params = {
                        strRoleName: $("#roleName").val(),
                        RoleID: $("#selRole").val()
                    };
                    table.reload('myTable', { where: params });
                });

                // 添加按钮事件
                $("#addBtn").click(function () {
                    // 重置表单
                    $("#roleId").val("");
                    $("#modalRoleName").val("").removeClass("layui-form-danger");
                    $("#modalDescription").val("");

                    layer.open({
                        type: 1,
                        title: "新增角色",
                        area: ["500px", "300px"],
                        content: $("#roleModal"),
                        btn: ["确认", "取消"],
                        btn1: function (index) {
                            var roleName = $("#modalRoleName").val().trim();
                            if (!roleName) {
                                $("#modalRoleName").addClass("layui-form-danger");
                                layer.tips('角色名称不能为空', '#modalRoleName', { tips: 1, time: 3000 });
                                return false;
                            }

                            var newRole = {
                                RoleName: roleName,
                                RoleReMark: $("#modalDescription").val().trim()
                            };

                            $.ajax({
                                type: "POST",
                                url: "/Role/AddRole",
                                data: newRole,
                                success: function (result) {
                                    if (result.success) {
                                        layer.msg(result.msg, { icon: 1 });
                                        layer.close(index);
                                        renderRoleTable();
                                        BindSelect();
                                    } else {
                                        layer.msg(result.msg, { icon: 2 });
                                    }
                                },
                                error: function () {
                                    layer.msg("网络错误，新增失败", { icon: 2 });
                                }
                            });
                        }
                    });
                });

                // 表格工具事件 - 同时处理编辑和删除
                table.on('tool(roleTableFilter)', function (obj) {
                    var data = obj.data;
                    var layEvent = obj.event;

                    // 验证数据有效性
                    if (!data || !data.RoleID) {
                        console.error("无效的数据或缺少RoleID");
                        layer.msg("数据错误，无法操作", { icon: 2 });
                        return;
                    }

                    // 编辑功能实现
                    if (layEvent === 'edit') {
                        console.log("执行编辑操作，角色ID: " + data.RoleID);

                        // 填充表单数据
                        $("#roleId").val(data.RoleID);
                        $("#modalRoleName").val(data.RoleName || "").removeClass("layui-form-danger");
                        $("#modalDescription").val(data.RoleReMark || "");

                        // 打开编辑模态框
                        layer.open({
                            type: 1,
                            title: "编辑角色",
                            area: ["500px", "300px"],
                            content: $("#roleModal"),
                            btn: ["确认修改", "取消"],
                            btn1: function (index) {
                                var roleName = $("#modalRoleName").val().trim();
                                if (!roleName) {
                                    $("#modalRoleName").addClass("layui-form-danger");
                                    layer.tips('角色名称不能为空', '#modalRoleName', { tips: 1, time: 3000 });
                                    return false;
                                }

                                var editRole = {
                                    RoleID: parseInt($("#roleId").val()),
                                    RoleName: roleName,
                                    RoleReMark: $("#modalDescription").val().trim()
                                };

                                $.ajax({
                                    type: "POST",
                                    url: "/Role/EditRole",
                                    contentType: "application/json; charset=utf-8",
                                    data: JSON.stringify(editRole),
                                    success: function (result) {
                                        if (result.success) {
                                            layer.msg(result.msg, { icon: 1 });
                                            layer.close(index);
                                            renderRoleTable();
                                            BindSelect();
                                        } else {
                                            layer.msg(result.msg, { icon: 2 });
                                        }
                                    },
                                    error: function (xhr) {
                                        console.error("编辑请求错误: ", xhr);
                                        layer.msg("编辑失败，状态码: " + xhr.status, { icon: 2 });
                                    }
                                });
                            }
                        });
                    }
                    // 删除功能实现
                    else if (layEvent === 'del') {
                        console.log("执行删除操作，角色ID: " + data.RoleID);

                        // 显示确认对话框
                        layer.confirm(
                            "确定要删除角色【" + (data.RoleName || "") + "】吗？",
                            {
                                icon: 3,
                                title: "删除确认"
                            },
                            function (confirmIndex) {
                                // 发送删除请求
                                $.ajax({
                                    type: "POST",
                                    url: "/Role/DeleteRole",
                                    data: { RoleID: data.RoleID },
                                    traditional: true,
                                    success: function (result) {
                                        if (result.success) {
                                            layer.msg(result.msg, { icon: 1 });
                                            obj.del(); // 从表格中移除该行
                                            BindSelect(); // 刷新下拉框
                                        } else {
                                            layer.msg(result.msg, { icon: 2 });
                                        }
                                    },
                                    error: function (xhr) {
                                        console.error("删除请求错误: ", xhr);
                                        layer.msg("删除失败，状态码: " + xhr.status, { icon: 2 });
                                    }
                                });

                                layer.close(confirmIndex);
                            }
                        );
                    }
                });

                // 加载下拉框数据
                function BindSelect() {
                    $.ajax({
                        type: "get",
                        url: "/Role/GetAllRoles",
                        dataType: "json",
                        success: function (result) {
                            $("#selRole option:not(:first)").remove();
                            if (result.error) {
                                layer.msg(result.error, { icon: 2 });
                                return;
                            }
                            var strHtml = "";
                            for (var i = 0; i < result.length; i++) {
                                strHtml += `<option value="${result[i].RoleID}">${result[i].RoleName}</option>`;
                            }
                            $("#selRole").append(strHtml);
                            form.render('select');
                        },
                        error: function (xhr) {
                            layer.msg("下拉框数据加载失败：" + xhr.statusText, { icon: 2 });
                        }
                    });
                }
            });
        });
    </script>
</body>
</html>
